package managedbean.SCM.DeliveryOrder;

import entity.CRM.LineItem;
import entity.CRM.SaleOrder;
import entity.SCM.ProductBalance;
import entity.SCM.ProductLine;
import java.awt.event.ActionEvent;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javaclass.ProductType;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import session.stateless.SCM.BatchBeanLocal;
import session.stateless.SCM.DeliveryOrderBeanLocal;

@ManagedBean(name = "addDeliveryOrderManagerBean")
@ViewScoped
public class AddDeliveryOrderManagerBean implements Serializable {

    public AddDeliveryOrderManagerBean() {
    }
    @EJB
    private DeliveryOrderBeanLocal deliveryOrderBeanLocal;
    @EJB
    private BatchBeanLocal batchBeanLocal;
    private List<ProductLine> productLines;
    private String statusMessage;
    
    private SaleOrder selectedSaleOrder;
    private List<ProductLine> tempProductLines = new ArrayList<ProductLine>();
    private List<ProductType> productTypes = new ArrayList<ProductType>();
    private ProductType productType;
    private Long quantity;

    public List<ProductLine> getProductLines() {
        return productLines;
    }

    public void setProductLines(List<ProductLine> productLines) {
        this.productLines = productLines;
    }

    public String getStatusMessage() {
        return statusMessage;
    }

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    public SaleOrder getSelectedSaleOrder() {
        return selectedSaleOrder;
    }

    public void setSelectedSaleOrder(SaleOrder selectedSaleOrder) {
        this.selectedSaleOrder = selectedSaleOrder;
    }

    public List<ProductLine> getTempProductLines() {
        return tempProductLines;
    }

    public void setTempProductLines(List<ProductLine> tempProductLines) {
        this.tempProductLines = tempProductLines;
    }

    public ProductType getProductType() {
        return productType;
    }

    public void setProductType(ProductType productType) {
        this.productType = productType;
    }

    public Long getQuantity() {
        return quantity;
    }
    
    public void setQuantity(Long quantity) {
        this.quantity = quantity;
    }
        
    public void setDisplayProductType(List<ProductType> productTypes){
        
        for(int i=0; i<selectedSaleOrder.getLineItems().size(); i++){
            ProductType displayProductType = selectedSaleOrder.getLineItems().get(i).getProductPrice().getProductType();
            productTypes.add(displayProductType);
        }
    }
    
    public List<ProductType> getDisplayProductType(){
        return productTypes;
    }
  
    public void initView(PhaseEvent event) {
        try {
            
            if(selectedSaleOrder == null){
                selectedSaleOrder = (SaleOrder)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("selectedSaleOrder");
                this.setDisplayProductType(productTypes);
            }
            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
   
    public void displayTempList(ActionEvent event) {
        try {

            Long validQuantity = deliveryOrderBeanLocal.quantityNeedToDelivery(selectedSaleOrder.getId(), getProductType());

            if (quantity.longValue() > validQuantity.longValue()) {
                FacesMessage message = new FacesMessage("Quantity allowed to delivery is:" + validQuantity + ". Please re-enter.");
                message.setSeverity(FacesMessage.SEVERITY_WARN);
                FacesContext.getCurrentInstance().addMessage("quantity", message);
            } else {
                for (int j = 0; j < productTypes.size(); j++) {
                    if (productTypes.get(j).equals(productType)) {
                        productTypes.remove(j);
                    }
                }

                ProductBalance product = batchBeanLocal.getProductBalance(productType);
                ProductLine productLine = new ProductLine();
                productLine.setProduct(product);
                productLine.setQuantity(quantity);

                //Daniel's add on to calculate price
                List<LineItem> temp_lineItems = this.getSelectedSaleOrder().getLineItems();
                Double temp_price = new Double(0);
                for (LineItem temp : temp_lineItems) {
                    if (temp.getProductPrice().getProductType() == productType) {
                        System.out.println("Successful");
                        temp_price = temp.getFinalPrice() * quantity / temp.getLineItemQuantity();
                        System.out.println("after calculatation" + temp_price);
                    }
                }
                productLine.setFinalPrice(temp_price);


                tempProductLines.add(productLine);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void saveDeliveryOrder(ActionEvent event) {
        try {
            List<ProductLine> productLineList = new ArrayList<ProductLine>();
            ProductLine productLine = new ProductLine();
            for (int i = 0; i < tempProductLines.size(); i++) {
                if (tempProductLines.get(i).getQuantity() != null && tempProductLines.get(i).getQuantity().longValue() > 0) {
                    productLine = deliveryOrderBeanLocal.createProductLine(tempProductLines.get(i).getProduct().getProductType(), tempProductLines.get(i).getQuantity(), tempProductLines.get(i).getFinalPrice());
                    productLineList.add(productLine);
                }
            }

            Long id = deliveryOrderBeanLocal.createDeliveryOrder(selectedSaleOrder.getId(),productLineList);

            if (id == null) {
                statusMessage = "Please Try Again.";
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful:" + statusMessage + "", ""));
            } else {

                boolean success = batchBeanLocal.completePickingOrder(id);

                if (success) {
                    statusMessage = "New Delivery Order " + id + " Saved Successfully.";
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, ""));
                } else {
                    statusMessage = "Error On Complete Picking Order.";
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful:" + statusMessage + "", ""));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
